<template>
  <div>
    <!-- 悬浮球按钮 -->
    <div
        class="chat-button"
        :class="{ 'open': isOpen }"
        @click="toggleChat"
        @mousedown="onMouseDown"
        :style="{ position: 'fixed', top: position.top + 'px', left: position.left + 'px', zIndex: 9999 }"
        ref="chatButtonRef"
    >
      <img src="@/assets/右上角AI助手.png" alt="AI助手" />
    </div>

    <!-- 聊天窗口 -->
    <div
        class="chat-window"
        :class="{ 'open': isOpen }"
        :style="{ position: 'fixed', top: chatWindowPosition.top + 'px', left: chatWindowPosition.left + 'px', zIndex: 9999 }"
        ref="chatWindowRef"
    >
      <!-- 窗口头部 -->
      <div class="chat-header">
        <h3>AI助手</h3>
        <button @click="toggleChat">
          <i class="fas fa-times"></i>
        </button>
      </div>
      <!-- 聊天内容区 -->
      <div class="chat-messages" ref="messagesContainer">
        <div
            v-for="(message, index) in messages"
            :key="index"
            :class="message.role === 'user' ? 'user-message' : 'assistant-message'"
        >
          <div class="avatar">
            <i :class="message.role === 'user' ? 'fas fa-user' : 'fas fa-robot'"></i>
          </div>
          <div class="message-content">
            <span v-if="message.role === 'user'" v-html="formatMessage(message.content)"></span>
            <span v-else v-html="formatMessage(displayedAssistantMessages[index - userMessageCount])"></span>
          </div>
        </div>
      </div>
      <!-- 输入区域 -->
      <div class="chat-input">
        <input
            type="text"
            v-model="userInput"
            @keyup.enter="sendMessage"
            placeholder="输入消息..."
        >
        <button @click="sendMessage">
          <i class="fas fa-paper-plane"></i>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue';

const isOpen = ref(false);
const messages = ref([]); // 所有消息
const userMessageCount = ref(0); // 用户消息计数
const assistantMessages = ref([]); // 仅存储助手消息
const displayedAssistantMessages = ref([]); // 助手消息的逐字内容
const userInput = ref('');
const chatButtonRef = ref(null);
const chatWindowRef = ref(null);
const messagesContainer = ref(null); // 聊天内容容器引用

// 拖拽相关
const position = ref({ top: 30, left: window.innerWidth - 180 }); // 初始位置
let dragging = false;
let offset = { x: 0, y: 0 };

const chatWindowWidth = 350;
const chatWindowHeight = 500;
const chatButtonSize = 150;

const chatWindowPosition = computed(() => {
  let left = position.value.left;
  let top = position.value.top + chatButtonSize + 10; // 10px 间距

  // 如果超出右侧
  if (left + chatWindowWidth > window.innerWidth) {
    left = window.innerWidth - chatWindowWidth - 10;
  }
  // 如果超出底部
  if (top + chatWindowHeight > window.innerHeight) {
    // 尝试显示在悬浮球上方
    if (position.value.top - chatWindowHeight - 10 > 0) {
      top = position.value.top - chatWindowHeight - 10;
    } else {
      // 贴底显示
      top = window.innerHeight - chatWindowHeight - 10;
    }
  }
  // 不让left为负
  if (left < 0) left = 10;
  if (top < 0) top = 10;
  return { left, top };
});

const onMouseDown = (e) => {
  if (e.button !== 0) return;
  dragging = true;
  offset.x = e.clientX - position.value.left;
  offset.y = e.clientY - position.value.top;
  document.addEventListener('mousemove', onMouseMove);
  document.addEventListener('mouseup', onMouseUp);
};

const onMouseMove = (e) => {
  if (!dragging) return;
  let newLeft = e.clientX - offset.x;
  let newTop = e.clientY - offset.y;
  newLeft = Math.max(0, Math.min(window.innerWidth - chatButtonSize, newLeft));
  newTop = Math.max(0, Math.min(window.innerHeight - chatButtonSize, newTop));
  position.value.left = newLeft;
  position.value.top = newTop;
};

const onMouseUp = () => {
  dragging = false;
  document.removeEventListener('mousemove', onMouseMove);
  document.removeEventListener('mouseup', onMouseUp);
};

onMounted(() => {
  if (position.value.left > window.innerWidth - chatButtonSize) {
    position.value.left = window.innerWidth - 180;
  }
});

function toggleChat() {
  isOpen.value = !isOpen.value;
}

// 滚动到新消息顶部的函数
const scrollToNewMessageTop = () => {
  if (messagesContainer.value) {
    const lastMessage = messagesContainer.value.lastElementChild;
    if (lastMessage) {
      messagesContainer.value.scrollTop = lastMessage.offsetTop;
    }
  }
};

// 将换行符替换为<br>的工具函数
const formatMessage = (text) => {
  if (!text) return '';
  return text.replace(/\n/g, '<br>');
};

async function sendMessage() {
  if (!userInput.value.trim()) return;

  // 添加用户消息
  const userMessage = {
    role: 'user',
    content: userInput.value
  };
  messages.value.push(userMessage);
  userMessageCount.value++; // 增加用户消息计数
  userInput.value = '';

  // // 立即滚动到新消息顶部
  // await nextTick(() => {
  //   scrollToNewMessageTop();
  // });

  try {
    const response = await fetch('http://localhost:80/ai/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        messages: messages.value
      })
    });

    if (response.ok) {
      const data = await response.json();
      const assistantMessage = {
        role: 'assistant',
        content: data.content
      };

      // 添加助手消息到独立数组
      const assistantIndex = assistantMessages.value.length;
      assistantMessages.value.push(assistantMessage);
      messages.value.push(assistantMessage);
      displayedAssistantMessages.value.push('');

      // 逐字显示逻辑
      const fullText = assistantMessage.content;
      let currentIndex = 0;

      const intervalId = setInterval(() => {
        if (currentIndex < fullText.length) {
          displayedAssistantMessages.value[assistantIndex] += fullText[currentIndex];
          currentIndex++;
          // 每次添加字符后滚动到新消息顶部
          // scrollToNewMessageTop();
        } else {
          clearInterval(intervalId);
        }
      }, 50); // 每40毫秒显示一个字符
    } else {
      console.error('Error:', response.status);
      const errorMessage = {
        role: 'assistant',
        content: '抱歉，发生了错误，请稍后再试。'
      };
      messages.value.push(errorMessage);
      assistantMessages.value.push(errorMessage);
      displayedAssistantMessages.value.push(errorMessage.content);
      scrollToNewMessageTop();
    }
  } catch (error) {
    console.error('Error:', error);
    const errorMessage = {
      role: 'assistant',
      content: '抱歉，连接服务器时发生了错误。'
    };
    messages.value.push(errorMessage);
    assistantMessages.value.push(errorMessage);
    displayedAssistantMessages.value.push(errorMessage.content);
    scrollToNewMessageTop();
  }
}
</script>

<style scoped>
/* 保持原有样式不变 */
.floating-chat {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.chat-button {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
  z-index: 1;
  border: none !important;
  box-shadow: none !important;
  /* 由JS动态设置fixed和top/left */
}

.chat-button img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.chat-button.open {
  transform: scale(0.9);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.chat-window {
  width: 350px;
  height: 500px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  opacity: 0;
  transform: translateY(20px) scale(0.95);
  transition: opacity 0.3s ease, transform 0.3s ease;
  visibility: hidden;
  /* 由JS动态设置fixed和top/left */
}

.chat-window.open {
  opacity: 1;
  transform: translateY(0) scale(1);
  visibility: visible;
}

.chat-header {
  background-color: #10224A;
  color: white;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-header h3 {
  margin: 0;
  font-weight: 500;
}

.chat-header button {
  background: none;
  border: none;
  color: white;
  font-size: 18px;
  cursor: pointer;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.user-message, .assistant-message {
  display: flex;
  gap: 10px;
  max-width: 90%;
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #165DFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.user-message .avatar {
  background-color: #E0E0E0;
  color: #333;
}

.message-content {
  background-color: #F0F0F0;
  padding: 10px 15px;
  border-radius: 15px;
  border-bottom-right-radius: 0;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.user-message .message-content {
  background-color: #165DFF;
  color: white;
  border-bottom-right-radius: 15px;
  border-bottom-left-radius: 0;
}

.message-content span {
  font-size: 13px; /* 可根据需要调整字体大小 */
}
.chat-input {
  padding: 15px 20px;
  border-top: 1px solid #E0E0E0;
  display: flex;
  gap: 10px;
}

.chat-input input {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #E0E0E0;
  border-radius: 20px;
  outline: none;
  font-size: 14px;
}

.chat-input button {
  background-color: #165DFF;
  color: white;
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.chat-input button:hover {
  background-color: #0E42B3;
}
</style>